<template>
<div>
    <Affix :offset-top="50">
        <Row :gutter="16" class="topBtnDiv">
            <Col span="4">
            <PartnersSelect v-if="CurUserInfo.IsShowAll" v-model="QueryModel.partnersId"></PartnersSelect>
            </Col>
            <Col span="4">
            <Button type="primary" icon="android-done" @click="AsycDict">同步到系统内存</Button>
            </Col>
        </Row>
    </Affix>
    <Row style="margin-top:20px">
        <Col>
        <div id="SystemModules"></div>
        </Col>
    </Row>

    <Modal v-model="Form.IsShow" :loading="Form.IsLoading" :title="Form.Title" @on-ok="Form.OkEvent" @on-cancel="Form.CancelEvent">
        <Form ref="EditForm" :model="Form.Data" label-position="top">
            <Row :gutter="16">
                <Col :xs="24" :md="12">
                <FormItem label="名称" prop="Name" :rules="{required: true, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="Form.Data.Name"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="12">
                <FormItem label="值" prop="Value">
                    <Input v-model="Form.Data.Value"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="24">
                <FormItem label="自定义属性" prop="Attr">
                    <Input v-model="Form.Data.Attr"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="12">
                <FormItem label="是否显示" prop="IsShowInMenu">
                    <i-switch v-model="Form.Data.IsShowInMenu">
                        <span slot="open">是</span>
                        <span slot="close">否</span>
                    </i-switch>
                </FormItem>
                </Col>

            </Row>
        </Form>
    </Modal>

    <Modal v-model="RollBackWin.IsShow" :loading="RollBackWin.IsLoading" title="恢复" @on-ok="DoRollBack">
        <Select v-model="RollBackWin.FileName">
            <Option v-for="item in FileNameList" :value="item" :key="item">{{ item }}</Option>
        </Select>
    </Modal>

</div>
</template>

<script>
import then from "thenjs";
import AppFrame from "../../../libs/app-frame";
import PartnersSelect from '../../../components/partners-select';
// var _model = {
//     'CarType': '车辆类型',
//     'Goods': '货物类型',
//     'Exception': '异常情况类型',
//     'Classes': '班次',
//     'RoadSection': '路段',
//     'OrgStructType': '稽查记录审核失败的原因',
//     'AdoptInfoAuditWrongCause': '稽查记录审核失败的原因'
// }
export default {
    components: {
        PartnersSelect
    },
    data: function () {
        let self = this;
        let MainData = {
            CurSelectNode: null,
            TreeData: []
        };
        let Form = {
            IsShow: false,
            IsLoading: true,
            Data: {},
            OkEvent: function () {
                self.$refs["EditForm"].validate(valid => {
                    if (valid) {
                        //console.log(Form.Data);

                        Form.Data.zd_partners_id = self.QueryModel.partnersId;
                        AppFrame.Http.Post(
                            "/manage-api/System/partners-dict/EditModule",
                            Form.Data,
                            function (err, ret) {
                                // console.log(ret);
                                if (ret && ret.Result == 1) {
                             
                                    var NodeData = self.GetNodeData(ret.Data);
                                    //console.log(NodeData);
                                    if (Form.Data.Type == "Edit") {
                                        self.EditNode(NodeData);
                                    } else {
                                        self.AddNode(NodeData);
                                    }
                                    Form.IsShow = false;
                                    self.$Message.success("操作成功");
                                } else {
                                    self.$Message.error("操作错误,请重试");
                                    Form.IsLoading = false;
                                    setTimeout(function () {
                                        Form.IsLoading = true;
                                    }, 0);
                                }
                            }
                        );
                    } else {
                        Form.IsLoading = false;
                        setTimeout(function () {
                            Form.IsLoading = true;
                        }, 0);
                    }
                });
            },
            CancelEvent: function () {},
            SelectModelIDEvent: function (value) {
                Form.Data.UrlGoModuleID = value;
                if (value == 0) {
                    Form.Data.URL = MainData.CurSelectNode.URL;
                } else if (value == -1) {
                    Form.Data.URL = "";
                } else {
                    for (var i in Form.Data.ChildrenNode) {
                        let item = Form.Data.ChildrenNode[i];
                        if (item.id == value) {
                            Form.Data.URL = item.a_attr.URL;
                        }
                    }
                }
            }
        };
        return {
            CurUserInfo: {},
            MainData: MainData,
            CurSelectNode: null,
            Form: Form,
            FileNameList: [],
            RollBackWin: {
                IsShow: false,
                IsLoading: true,
                FileName: ""
            },
            QueryModel: {
                partnersId: -1
            }
            //label:""
        };
    },
    created() {
        // this.label=this.$route.params.label;
        this.CurUserInfo = AppFrame.UserInfo.getUserInfo();
        this.renderTree();
    },
    watch: {
        $route: function () {
            //当路由改变时
            let self = this;
            self.renderTree(true);
        },
        "QueryModel.partnersId": function (curVal, oldVal) {
            this.renderTree(true);
        }
    },
    methods: {
        GetTreeData(cb) {
            let self = this;
            var _TreeData = [];

            _TreeData.push({
                id: 0,
                text: self.$route.query.dictname || "系统字典",
                parent: "#",
                icon: "fa fa-folder"
            });
            //console.log(self.$route.params.label);
            then(function (defer) {
                    let PostData = {
                        partnersID: self.QueryModel.partnersId
                    };

                    AppFrame.Http.Post("/manage-api/system/partners-dict/getItems?label=" + self.$route.params.label, PostData, defer);
                }).then(function (defer, ret) {

                    if (ret && ret.Result == 1) {
                        defer(null, ret.Data);
                    } else {
                        defer({
                            Result: 0
                        });
                    }
                })
                .fin(function (defer, err, ret) {
                    if (err) {
                        if (cb) cb(err);
                    } else {
                        // console.log(ret);
                        ret.map(function (item) {
                            var Node = self.GetNodeData(item);
                            _TreeData.push(Node);
                        });
                        //console.log(_TreeData);
                        if (cb) cb(null, _TreeData);
                    }
                });
        },

        GetNodeData(Module) {
            var Node = {
                id: Module.zd_ID,
                parent: Module.zd_ParentID,
                text: Module.zd_Name,
                type: Module.zd_IsParent == 1 ? "parent" : "children",
                a_attr: {
                    //自定义a标签的属性
                    DictID: Module.zd_ID,
                    Name: Module.zd_Name,
                    ParentID: Module.zd_ParentID,
                    IsParent: Module.zd_IsParent,
                    //Icon: Module.Icon,
                    Value: Module.zd_value,
                    Sort: Module.zd_sort,
                    Label: Module.zd_label,
                    // UrlGoModuleID: Module.UrlGoModuleID,
                    // Able: Module.Able,
                    IsShowInMenu: Module.zd_IsShow ? true : false,
                    Attr: Module.zd_Attr
                    //Remark: Module.Remark
                }
            };
            return Node;
        },

        RenderEditForm(type, node, labelName) {
            var self = this;
            var TreeData = self.MainData.TreeData;
            self.Form.Title = "添加下级菜单";
            var Model = {
                Type: type
            };

            if (node) {
                Model.ParentID = node.a_attr.ParentID;
                Model.DictID = node.a_attr.DictID;
                Model.Name = node.a_attr.Name;
                Model.Value = node.a_attr.Value;
                Model.IsShowInMenu = node.a_attr.IsShowInMenu ? true : false;
                Model.Attr = node.a_attr.Attr;
                Model.Label = node.a_attr.label; //类型
                Model.ChildrenNode = [];
                for (var i = 1; i < TreeData.length; i++) {
                    if (TreeData[i].a_attr.ParentID == Model.zd_ID) {
                        Model.ChildrenNode.push(TreeData[i]);
                    }
                }
                self.Form.Title = "修改 - " + Model.Name;
            } else {
                Model.ParentID = this.MainData.CurSelectNode.id;
                Model.ChildrenNode = [];
                Model.DictID = 0;
                Model.Name = "";
                Model.Value = "";
                Model.Attr = "";
                Model.Label = self.$route.params.label; //类型
                Model.IsShowInMenu = false;
                if (labelName) {
                    Model.Label = labelName;
                }
                //Model.Remark = "";
                //Model.Able = "";
                // Model.UrlGoModuleID = 0;
            }
            self.Form.IsShow = true;
            self.Form.Data = Model;
        },

        renderTree(isReflash) {
            let self = this;
            /**初始化JsTree */
            function InitSystemModules() {
                let tree = null;

                function initJsTree(TreeData) {
                    // console.log(TreeData);
                    // if (self.tree != null) {
                    //   alert(11);
                    //   self.tree.destroy();
                    // }
                    $("#SystemModules").on("select_node.jstree", function (e, data) {
                        self.MainData.CurSelectNode = data.node;
                    });

                    $("#SystemModules").on("move_node.jstree", function (e, data) {
                        var TargetNode = tree.get_node(data.parent);
                        var PostData = {
                            CurNodeID: data.node.id,
                            TargetParentID: data.parent,
                            old_parent: data.old_parent,
                            TargetNodeChildrensIDs: TargetNode.children.join(",")
                        };
                        self.CheckIsParent(PostData.TargetParentID);
                        self.CheckIsParent(data.old_parent);
                        AppFrame.Http.Post(
                            "/manage-api/system/partners-dict/MoveNode",
                            PostData,
                            function (BackData) {
                                if (BackData.Result == 0) {
                                    self.$Message.success(BackData.Msg);
                                }
                            }
                        );
                    });

                    $("#SystemModules").jstree({
                        core: {
                            multiple: false,
                            themes: {
                                variant: "large",
                                responsive: false
                            },
                            // so that create works
                            check_callback: true,
                            data: TreeData
                        },
                        types: {
                            default: {
                                icon: " fa fa-link"
                            },
                            parent: {
                                icon: " fa fa-bookmark"
                            }
                        },
                        plugins: ["wholerow", "contextmenu", "dnd", "types"],
                        // "state": {
                        //     "key": "SystemModules"
                        // },
                        contextmenu: {
                            items: contextmenu
                        }
                    });

                    tree = $.jstree.reference("#SystemModules");
                }

                self.GetTreeData(function (err, TreeData) {
                    self.MainData.TreeData = TreeData;

                    if (isReflash) {
                        let tree = $.jstree.reference("#SystemModules");
                        tree.settings.core.data = TreeData;
                        tree.refresh();
                    } else {
                        initJsTree(TreeData);
                    }
                });
            }

            function contextmenu(node) {
                var items = {
                    edititem: {
                        label: "修改",
                        icon: "glyphicon glyphicon-edit ",
                        action: function () {
                            self.RenderEditForm("Edit", node);
                        }
                    },
                    deleteitem: {
                        label: "删除",
                        icon: "glyphicon glyphicon-remove   ",
                        action: function () {
                            self.DeleteNode(node);
                        }
                    },
                    additem: {
                        label: "添加下级",
                        icon: "glyphicon glyphicon-saved ",
                        action: function () {
                            self.RenderEditForm("Add", "", node.a_attr.Label);
                        }
                    }
                };

                if (node.parent == "#") {
                    delete items.lookitem;
                    delete items.deleteitem;
                    delete items.edititem;
                }

                return items;
            }

            InitSystemModules();
        },

        /**
         * 添加 节点
         * @param NodeData
         * @constructor
         */
        AddNode(NodeData) {
            var CurSelectNode = this.MainData.CurSelectNode;
            var tree = $.jstree.reference("#SystemModules");
            tree.create_node(CurSelectNode, NodeData);
            this.CheckIsParent(CurSelectNode.id);
            tree.open_node(CurSelectNode);
            tree.deselect_all();
            tree.select_node(NodeData);
            this.MainData.TreeData.push(NodeData);
        },

        /**
         * 编辑 节点
         * @param NodeData
         * @constructor
         */
        EditNode(NodeData) {
            var CurSelectNode = this.MainData.CurSelectNode;
            CurSelectNode.a_attr = NodeData.a_attr;
            CurSelectNode.text = NodeData.text;
            $.jstree
                .reference("#SystemModules")
                .set_text(CurSelectNode, NodeData.text);
        },

        /**
         * 删除节点
         * @param NodeData
         * @constructor
         */
        DeleteNode(node) {
            var self = this;
            this.$Modal.confirm({
                title: "提示",
                content: "确实要删除 [" + node.text + "] 吗?",
                loading: true,
                onCancel: () => {
                    self.$Modal.remove();
                },
                onOk: () => {
                    var AllIchildrenIDs = node.children_d;
                    var AllIDs = AllIchildrenIDs.join(",") + "," + node.id;
                    var PostData = {
                        AllIDs: AllIDs,
                        CurNodeID: node.id,
                        CurNodeParentID: node.a_attr.ParentID
                    };

                    var tree = $.jstree.reference("#SystemModules");
                    tree.delete_node(node);
                    self.CheckIsParent(node.a_attr.ParentID);
                    var AllIDsArray = AllIDs.split(",");
                    for (var id in AllIDsArray) {
                        if (AllIDsArray[id] != "") {
                            for (var i = self.MainData.TreeData.length - 1; i >= 0; i--) {
                                if (self.MainData.TreeData[i].id == Number(AllIDsArray[id])) {
                                    self.MainData.TreeData.splice(i, 1);
                                    break;
                                }
                            }
                        }
                    }

                    AppFrame.Http.Post(
                        "/manage-api/System/partners-dict/DelModule",
                        PostData,
                        function (err, BackData) {
                            self.$Modal.remove();
                            if (BackData && BackData.Result == 1) {
                                self.$Message.success("操作成功");
                            } else {
                                self.$Message.error("操作失败");
                            }
                        }
                    );
                }
            });
        },

        AsycDict() {
            let self = this;
            AppFrame.Http.Post("/manage-api/System/partners-dict/AsycDict", {}, function (
                err,
                ret
            ) {
                // console.log('AsycDict');
                // console.log(ret);
                if (ret && ret.Result == 1) {
                    self.$Message.success("操作成功");
                } else {
                    self.$Message.error("操作失败");
                }
            });
        },

        RollBack() {
            var self = this;
            this.RollBackWin.IsShow = true;
            AppFrame.Http.Post("/manage-api/system/partners-dict/GetJsonFile", {}, function (
                err,
                ret
            ) {
                if (ret && ret.Result == 1) {
                    self.FileNameList = ret.Data;
                }
            });
        },
        DoRollBack() {
            var self = this;
            var selectFileName = self.RollBackWin.FileName;
            if (selectFileName == "") {
                self.$Message.error("请选择需要恢复的文件");
                self.RollBackWin.IsLoading = false;
                setTimeout(function () {
                    self.RollBackWin.IsLoading = true;
                }, 0);
            }
            AppFrame.Http.Post(
                "/system/partners-dict/RollBack", {
                    FileName: selectFileName
                },
                function (err, ret) {
                    if (ret && ret.Result == 1) {
                        self.RollBackWin.IsShow = false;
                        self.$Message.success("恢复成功");
                    }
                }
            );
        },

        /**
         * 检测是否是父级
         * @param NodeID
         * @constructor
         */
        CheckIsParent(NodeID) {
            if (NodeID == 0) return;
            var tree = $.jstree.reference("#SystemModules");
            var ParentNode = tree.get_node(NodeID);
            if (ParentNode) {
                if (ParentNode.children.length > 0) {
                    ParentNode.type = "parent";
                    ParentNode.a_attr.IsParent = 1;
                    tree.set_icon(ParentNode, "fa fa-bookmark ");
                } else {
                    ParentNode.type = "children";
                    ParentNode.a_attr.IsParent = 0;
                    tree.set_icon(ParentNode, "fa fa-link   ");
                }
            }
        }
    }
};
</script>

<style scoped>
.topBtnDiv {
    line-height: 40px;
    background-color: #fff;
}
</style>
